﻿using iTool.SQL.Analysis.Context;
using iTool.SQL.Analysis.Context.Options;
using iTool.SQL.Analysis.Context.SQLWhereOptions;
using iTool.SQL.Analysis.TableConstructorInsert;

using Microsoft.SqlServer.Management.SqlParser.SqlCodeDom;
using System;
using System.Collections.Generic;
using System.Text;

namespace iTool.SQL.Analysis.SubQuery
{
    /// <summary>
    /// 子查询
    /// </summary>
    public class SqlQuerySpecificationAnalysis : SqlAnalysisBase
    {
        public SqlQuerySpecificationAnalysis(SqlAnalysisContext context) : base(context)
        {
        }

        public override void Analysis()
        {
            if (base.Parent == null)
            {
                base.Next();
                return;
            }

            switch (base.CodeObject.Parent.Parent)
            {
                // insert
                case var t when t is SqlRowConstructorExpression:
                    base.AnalysisSubQuery();
                    ((SqlInsertAnalysisContext)base.context).Sets[base.Parent.Index].Value = $"$query_{context.ChildrenQuerys?.Count ?? 0}";
                    break;

                // update
                case var t when t is SqlAssignment && base.context is SqlUpdateAnalysisContext uContext:
                    base.AnalysisSubQuery();
                    uContext.Sets[^1].Value = $"$query_{context.ChildrenQuerys?.Count ?? 0}";
                    break;

                case var t when t is SqlSelectScalarExpression && base.context is SqlSelectAnalysisContext sContext:
                    base.AnalysisSubQuery();
                    sContext.QueryFields.Add(new SQLFieldOptions
                    {
                        Name = $"$query_{context.ChildrenQuerys?.Count ?? 0}"
                    });
                    break;

                // 条件表达式
                case var t when t is SqlBooleanExpression:
                    base.AnalysisSubQuery();
                    var where = (WhereOptions)base.WhereOptions;
                    if (where.Left == null
                        && where.ComparisonBooleanExpressionType != ComparisonBooleanExpressionType.Exists
                        && where.ComparisonBooleanExpressionType != ComparisonBooleanExpressionType.NotExists)
                    {
                        where.Left = new SubQueryOptions(base.context.ChildrenQuerys);
                    }
                    else if (where.Right == null)
                    {
                        where.Right = new SubQueryOptions(base.context.ChildrenQuerys);
                    }

                    //StringBuilder where = base.GetWhereBuilder();
                    //where.Append($" $query_{context.ChildrenQuerys.Count}");
                    break;
                default:
                    base.Next();
                    break;
            }

        }

        public override bool Validation(SqlCodeObject codeObject) => true;
    }
}
